<?php

namespace App\Trip\Orders\BookOrders\Train\SelectedSeats;

use App\Trip\Train\Seat\Seats;
use Exception;
use Illuminate\Support\Str;

class BuildOrderSelectedSeats extends SelectedSeats
{
    use TraitParseSelectedSeats;

    private Seats $current_seat;
    private int   $seat_type;

    /**
     * @throws Exception
     */
    public function __construct(Seats $current_seat, array $selected_seats)
    {
        $this->current_seat   = $current_seat;
        $this->selected_seats = $selected_seats;
        $this->seat_type      = $this->current_seat->getSeatType();
        $this->buildSeatsOrderBeds();
    }

    public function getSeatType(): int
    {
        return $this->seat_type;
    }

    /**
     * 解析 硬座 卧铺 靠窗等
     *
     * @throws Exception
     */
    private function buildSeatsOrderBeds(): void
    {

        if (empty($this->selected_seats)) {
            return;
        }
        $can_select_seats = $this->current_seat->canSelectSeats();

        foreach ($this->selected_seats as $key => $seat) {
            if (in_array($seat['seat'], Seats::SEAT_SIDES)) {
                $match_seats = collect($can_select_seats)->map(function ($can_select_seat) use ($seat) {
                    if (Str::contains($can_select_seat['side'], $seat["seat"])) {
                        return $can_select_seat;
                    }
                })->filter();
            } else {
                $match_seats = collect($can_select_seats)->where('seat', $seat['seat']);
            }

            if (!$match_seats->count()) {
                throw new Exception("选座错误，当前车次没有座位"."{$seat['seat']}", 404);
            }
            /**
             * 用第一条匹配
             * seats 只要匹配到这里面的数据 就算匹配
             */
            $match_seat = $match_seats->first();
            $seats      = $match_seats->implode('seat', ',');

            if (!isset($this->build_seats[$seat['seat']])) {
                $this->build_seats[$seat['seat']] = [
                    'seat_type'   => $this->seat_type,
                    'seat'        => $seat['seat'],
                    'seats'       => $seats,
                    'service_fee' => $match_seat['service_fee'],
                    'count'       => $seat['count'] ?? 1,
                ];
            } else {
                isset($seat['count']) ? $this->build_seats[$seat['seat']]['count'] = $seat['count'] : $this->build_seats[$seat['seat']]['count']++;
            }
        }
    }


    public function __toString(): string
    {
        return json_encode($this->getSelectedSeats(), JSON_UNESCAPED_UNICODE) ?: '';
    }

    public function getSelectedSeats(): array
    {
        return $this->build_seats;
    }
}